from selenium.webdriver.common.by import By
from pages.base_page import Page
import random


class SegmentationPage(Page):
    segment_name = 'autotest' + str(random.randint(1, 1000))

    ele_title = (By.ID, u'page-segment-title')
    ele_enable_segmentation = (By.XPATH, u"//span[@data-tag='featureSwitch']")
    ele_new_segment_button = (By.XPATH, u"//span[text()='New Segment']")
    ele_segment_table = (By.XPATH, u'//thead/tr')

    ele_name = (By.ID, u'form-segment-input-name')
    ele_save_button = (By.XPATH, u"//span[text()='Save']")
    ele_enable = (By.XPATH, u"//div[text()='Enable']")
    ele_delete_button = (By.XPATH, u"//tr[last()]//td[@data-tag='operation'][last()]//button[last()]")
    ele_confirm_delete = (By.XPATH, u"//span[text()='Delete']")

    ele_error = (By.XPATH, u'//div[@role="alert"]')

    # No feature
    ele_no_feature_title = (By.ID, u'undefined-title')
    ele_no_feature_image = (By.XPATH, u"//h3[text()='Feature Introduction']")
    ele_unlock_feature_button = (By.XPATH, u"//span[text()='Unlock This Feature']")

    def __init__(self, driver, url, site_id):
        Page.__init__(self, driver, url)
        self.site_id = site_id
        self.url = url

    def check_if_segmentation_enable(self):
        fs = self.find_element(*self.ele_enable_segmentation)
        if fs.text == 'OFF':
            self.click(self.ele_enable_segmentation)
        else:
            pass

    def check_page_has_error(self):
        try:
            flag = self.find_element(*self.ele_error).is_enabled()
            if flag:
                raise Exception("current page {} may has error".format(self.url))
        except Exception as e:
            return True

    def segmentation_eles_check_when_has_feature(self):
        self.find_element(*self.ele_title).is_enabled()
        self.find_element(*self.ele_new_segment_button).is_enabled()
        self.find_element(*self.ele_segment_table).is_enabled()

        # create
        self.click(self.ele_new_segment_button)
        self.input_text(self.ele_name, self.segment_name)
        self.click(self.ele_enable)
        self.click(self.ele_save_button)

        # delete
        self.click(self.ele_delete_button)
        self.click(self.ele_confirm_delete)

    def segmentation_eles_check_when_no_feature(self):
        self.find_element(*self.ele_no_feature_title).is_enabled()
        self.find_element(*self.ele_no_feature_image).is_enabled()
        self.find_element(*self.ele_unlock_feature_button).is_enabled()
